package com.olc.railing.socket;

import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import java.io.BufferedInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;

public class SocketClient {
    //类初始化时，不初始化这个对象(延时加载，真正用的时候再创建)
    private static final String TAG = SocketClient.class.getSimpleName();
    private static  String mIp = ""; //192.168.12.181
    private static  int mPort;
    private static Socket socket;
    private static Handler mainHandler;
    private Callback callback;
    private ExecutorService executorService = Executors.newFixedThreadPool(6,new ThreadFactory() {
        @Override
        public Thread newThread(Runnable r) {
            return new Thread(r);
        }
    });

    //构造器私有化
    public SocketClient(String ip,int port,Callback callback) {
        this.callback = callback;
        mIp = ip;
        mPort = port;
        Log.d(TAG,"mIp: "+mIp+" mPort: "+mPort);
        mainHandler = new Handler(Looper.getMainLooper());
        Log.d(TAG,"socket: "+socket);
        callback.onConnectSucces(mIp+":"+ mPort);

    }
    public void sendStrData(String reqeuest){
        Log.d(TAG,"sendStrData reqeuest: "+reqeuest);
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    socket = new Socket(mIp, mPort);
                    socket.setKeepAlive(true);

                    // 1、获取输出流，向服务器端发送信息
                    OutputStream  os = new DataOutputStream(socket.getOutputStream());
                    // 2、传送给服务器
                    os.write(reqeuest.getBytes("UTF-8"));
                    os.flush();

                    String  response = recevStrData();
                    Log.d(TAG,"接收成功 response: "+response);
                    mainHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            callback.call(response);
                        }
                    });
                    os.close();
                 //   Thread.sleep(5000);
                    closeSocket();
                } catch (IOException ioException) {
                    ioException.printStackTrace();
                }
            }
        });


    }
    public byte[] recevByteData() throws IOException {
        // 从服务器接收返回的数据
        BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
        //处理认证响应报文
        byte[] receiveBytes = new byte[1024];
        // 定义一个长度为8K字节的数组用来存放服务器返回的结果
        byte[] bufferedBytes = new byte[1024];
        int len, lastLen = 0;
        if ((len = bis.read(receiveBytes)) != -1) {
            System.arraycopy(receiveBytes, 0, bufferedBytes, lastLen, len);
            lastLen += len;
        }
        Log.d(TAG,"lastLen: "+lastLen);
        byte[] responseData = new byte[lastLen];
        System.arraycopy(bufferedBytes, 0, responseData, 0, responseData.length);
        bis.close();
        return responseData;
    }

    public String recevStrData() throws IOException {
        byte[] responseData = recevByteData();
        return new String(responseData, "UTF-8");
    }
    public void closeSocket(){
        try {
            if(socket!=null&&socket.isConnected()){
                socket.close();
            }
            socket = null;
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }
    }

}
